//
//  CHDHomeVC.m
//  IOSWeiiPhoneNews
//
//  Created by ibokan on 14-4-23.
//  Copyright (c) 2014年 chen. All rights reserved.
//

#import "CHDHomeVC.h"
#import "TFHpple.h"
#import "EGOImageView.h"
#import "MJRefresh.h"
#import "CHDHomeModel.h"
#import "CHDDetailsVC.h"
#import "CHDmyCollectionVC.h"

#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width
#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height
@interface CHDHomeVC ()
{
    
    MJRefreshHeaderView *_header;
    MJRefreshFooterView *_footer;
    
}
@end

@implementation CHDHomeVC
bool isExistenceNetwork;//判断是否有网络
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    //设置当前视图的背景颜色为灰色
    self.view.backgroundColor=[UIColor grayColor];
    //初始化要用到的可变数组

    self.arrTitle=[[NSMutableArray alloc]initWithCapacity:0];
    
    self.authorAry=[[NSMutableArray alloc]initWithCapacity:0];
    self.models=[[NSMutableArray alloc]initWithCapacity:0];
    //设置开始解析网址
    self.urlStr = @"http://www.feng.com/iPhone/index.shtml";
    
    //设置scrollView的坐标以显示图片
    self.scrollView=[[UIScrollView alloc]initWithFrame:CGRectMake(0, 65, SCREEN_WIDTH, 150)];
    //设置scrollView是否可以翻页 是为yes
    self.scrollView.pagingEnabled=YES;
    //设置scrollView是否可以交互 no为不可以
    self.scrollView.userInteractionEnabled=NO;
    self.scrollView.layer.borderWidth=1;
    //ios7.0新特性 设置scrollView是否下移
    self.automaticallyAdjustsScrollViewInsets=NO;

    //设置滚动图片的标题的坐标 字体 颜色 以及贴到视图上
    self.titleLabel=[[UILabel alloc]initWithFrame:CGRectMake(0, 220, SCREEN_WIDTH, 20)];
    //    self.titleLabel.backgroundColor=[UIColor redColor];
    self.titleLabel.font=[UIFont fontWithName:nil size:15];
    self.titleLabel.textColor=[UIColor greenColor];
    [self.view addSubview:self.titleLabel];

    
    //设置表格的坐标 代理 以及是否隐藏
    self.tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 240, SCREEN_WIDTH, SCREEN_HEIGHT-280) style:UITableViewStylePlain];
    self.tableView.delegate=self;
    self.tableView.dataSource=self;
    //设置表格边框
    self.tableView.layer.borderWidth=1;
    self.tableView.separatorColor=[UIColor blackColor];
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine];
    self.tableView.hidden=YES;
    [self.view addSubview:self.tableView];
    
    self.button=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    self.button.frame=CGRectMake(0, 0, 80,35);
    [self.button setTitle:@"iPhone" forState:UIControlStateNormal];
    
    //设置点击标题时显示不同的背景颜色的方法
    //[self.button addTarget:self action:@selector(changeBackgroundColor) forControlEvents:UIControlEventTouchDown];
    [self.button setImage:[UIImage imageNamed:@"more"] forState:UIControlStateNormal];
    
    [self.button addTarget:self action:@selector(printControlView) forControlEvents:UIControlEventTouchUpInside];
    //设置导航条的标题视图坐标 并将按钮贴上去
    self.navigationItem.titleView.frame=CGRectMake(120,80 , 100, 80);
    self.navigationItem.titleView=self.button;
    //设置导航条右边的按钮的标题收藏
    UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithTitle:@"收藏" style:UIBarButtonItemStylePlain target:self action:@selector(MyCollection)];
    self.navigationItem.rightBarButtonItem = rightButton;
    //设置导航条左边按钮为刷新图案
    UIBarButtonItem *leftBarBtnItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(refreshTable)];
    self.navigationItem.leftBarButtonItem = leftBarBtnItem;
    //创建定时器 以让图片定时滚动
    [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(moveImg) userInfo:nil repeats:YES];
    
    // 3.集成刷新控件
    // 3.1.下拉刷新
    [self addHeader];
    
    // 3.2.上拉加载更多
    [self addFooter];
    //判断有无网络连接方法
    
    //判断有无网络连接方法
    [self performSelector:@selector(notificationCenter)];
    
}
//设置点击标题时显示不同的背景颜色的方法的实现
-(void)changeBackgroundColor{
    
    self.button.backgroundColor = [UIColor colorWithRed:arc4random()%256/255.0 green:arc4random()%256/255.0 blue:arc4random()%256/255.0 alpha:arc4random()%256/255.0];
}
//收藏
-(void)MyCollection{
    [self.navigationController pushViewController:[CHDmyCollectionVC new] animated:YES];
    
}
//刷新
-(void)refreshTable{
    //判断当前网络是否连接 然后调用不同方法
    if (isExistenceNetwork == NO){
        [self showNoNetWork];
    }else{
        [self performSelector:@selector(downImgData)];
        
    }

    
}
//标题点击事件
-(void)printControlView{
    //设置是否显示下拉框控制器为yes
    self.isControlShow=YES;
    //判断表视图是否隐藏 没有则设置隐藏
    if (self.tableView.hidden==NO) {
        self.tableView.hidden=YES;
    }
    //判断下拉框控制器是否显示 显示则移除控制器
    if (self.isControlShow) {
        [self.control removeFromSuperview];
    }
    
    //设置下拉框控制器的坐标
    self.control=[[UIControl alloc]initWithFrame:CGRectMake(110, 70, 100,80)];
    //创建新的表视图 用于显示下拉框内容
    UITableView*table=[[UITableView alloc]initWithFrame:self.control.bounds style:UITableViewStylePlain];
    //设置代理
    table.delegate=self;
    table.dataSource=self;
    //边框宽度 颜色
    table.layer.borderWidth=1;
    table.layer.borderColor=[[UIColor grayColor]CGColor];
    
    
    //设置行间隔边框
    table.separatorColor = [UIColor clearColor];
    [self.control addSubview: table];
    //下拉框内容
    self.nameAry=[NSMutableArray arrayWithObjects:@"iPhone",@"iPad",@"apple",@"gphone",@"palmpre", nil];
    //添加执行方法
    [self.control addTarget:self.control action:@selector(clickView:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:self.control];

    
}
-(void)clickView:(NSInteger)index{
    //判断下拉框内容被单击的单元格 ，把标题按钮的标题以及标题label的内容设置为当前选择的内容
    //然后移除下拉框控制器 并设置显示为NO 同时移除数组中得所有数据 同时执行方法
    switch (index) {
        case 0:
  
            
            [self.button setTitle:self.nameAry[index] forState:UIControlStateNormal];
            self.button.titleLabel.text=@"iPhone";
            self.urlStr = @"http://www.feng.com/iPhone/index.shtml";
            
            [self.control removeFromSuperview];
            self.isControlShow=NO;
            
            [self.arrTitle removeAllObjects];
            [self.authorAry removeAllObjects];
            [self.models removeAllObjects];
            [self performSelector:@selector(downImgData)];
            // NSLog(@"%@",self.button.titleLabel.text);
            
            break;
        case 1:

            
            [self.button setTitle:self.nameAry[index] forState:UIControlStateNormal];
            self.button.titleLabel.text=@"iPad";
            self.urlStr = @"http://www.feng.com/iPad/index.shtml";
            
            [self.control removeFromSuperview];
            self.isControlShow=NO;
            [self.arrTitle removeAllObjects];
            [self.authorAry removeAllObjects];
             [self.models removeAllObjects];
            [self performSelector:@selector(downImgData)];
            //NSLog(@"%@",self.button.titleLabel.text);
            break;
        case 2:
            
            [self.button setTitle:self.nameAry[index] forState:UIControlStateNormal];
            self.button.titleLabel.text=@"apple";
            self.urlStr = @"http://www.feng.com/apple/index.shtml";
            
            [self.control removeFromSuperview];
            self.isControlShow=NO;
            [self.arrTitle removeAllObjects];
            [self.authorAry removeAllObjects];
             [self.models removeAllObjects];
            [self performSelector:@selector(downImgData)];
            
            break;
        case 3:
            
            [self.button setTitle:self.nameAry[index] forState:UIControlStateNormal];
            self.button.titleLabel.text=@"gphone";
            
            self.urlStr = @"http://www.feng.com/gphone/index.shtml";
            
            [self.control removeFromSuperview];
            self.isControlShow=NO;
            [self.arrTitle removeAllObjects];
            [self.authorAry removeAllObjects];
             [self.models removeAllObjects];
            [self performSelector:@selector(downImgData)];
            
            break;
        case 4:
            
            [self.button setTitle:self.nameAry[index] forState:UIControlStateNormal];
            self.button.titleLabel.text=@"palmpre";
            self.urlStr = @"http://www.feng.com/palmpre/index.shtml";
            
            [self.control removeFromSuperview];
            self.isControlShow=NO;
            [self.arrTitle removeAllObjects];
            [self.authorAry removeAllObjects];
             [self.models removeAllObjects];
            [self performSelector:@selector(downImgData)];
            
            break;
            
        default:
            break;
    }
    
}

//图片移动方法
-(void)moveImg{
    //设置静态局部变量
    static int i=0;
    //NSLog(@"%@",self.arrTitle);
    
    if (i>4) {
        i=0;
    }
    self.scrollView.contentOffset=CGPointMake(320*i, 0);
    
    //防止空数组报错 判断数组是否有值 有则执行
    if (self.arrTitle.count<=0) {
        
        
    }else{
        
        if (self.scrollView.contentOffset.x==i*320) {
            self.titleLabel.text=self.arrTitle[i];
        }
    }
    i++;
}
-(void)downImgData{
    //将无网络视图移除掉
    [self.reachability removeFromSuperview];
    
    NSString* urlStr=@"http://www.feng.com";
    NSURL * url = [NSURL URLWithString:urlStr];
    NSURLRequest * request = [NSURLRequest requestWithURL:url];
    //异步加载
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse * response, NSData * data, NSError * error)
     {
         //展示一下由网址获得的html 数据格式
         // NSString * str = [[NSString alloc] initWithData:data encoding: NSUTF8StringEncoding];
         // NSLog(@"%@",str);
         //xpath解析html
         self.xpathParser=[[TFHpple alloc]initWithHTMLData:data];
         
         
         //获取解析下来得图片数据数组
         NSArray * arrArticleTitle = [self.xpathParser searchWithXPathQuery:@"//div[@id='hot5_big']//div[@class='changeDiv']//a/img/@src"];
         
         for (int i=0; i<arrArticleTitle.count; i++) {
             //获取元素的内容
             TFHppleElement *element1 =[arrArticleTitle objectAtIndex:i];
             NSString *myContent = [element1 content];
             //NSLog(@"%@",myContent);
             //设置图片加载前的默认图片
             self.imageView = [[EGOImageView alloc] initWithPlaceholderImage:[UIImage imageNamed:@"1.jpg"]];
             //设置图片的坐标
             [self.imageView setFrame:CGRectMake(i*320, 0, 320, 150)];
             //根据图片url解析图片
             [self.imageView setImageURL:[NSURL URLWithString:myContent]];
             //设置scrollView的内容尺寸
             self.scrollView.contentSize=CGSizeMake(320*i, 150);
             [self.scrollView addSubview:self.imageView];
             
             [self.view addSubview:self.scrollView];
         }
         
         NSArray * arrTitle1 = [self.xpathParser searchWithXPathQuery:@"//div[@id='hot5_big']//div[@class='changeDiv']//a"];
         for (int i=0; i<arrTitle1.count; i++) {
             if (i%2==0) {
                 TFHppleElement *elementNew =[arrTitle1 objectAtIndex:i];
                 NSString *myContent5 = [elementNew content];
                 [self.arrTitle addObject:myContent5];
                 // NSLog(@"%@",myContent5);
             }
             // NSLog(@"1=%ld",self.arrTitle.count);
         }
         
         
     }];
    [self performSelector:@selector(downNewsData)];
}
-(void)downNewsData{
    [self showHUD];
    //将无网络视图移除掉
    if (self.reachability) {
        [self.reachability removeFromSuperview];
    }
    
//    //将刷新标示显示出来并开始旋转
//    self.activityIndicator.hidden=NO;
//    [self.activityIndicator startAnimating];
    //取消表视图的移除
    self.tableView.hidden=NO;
    //网络解析
    NSURL * url = [NSURL URLWithString:self.urlStr];
    NSLog(@"%@",url);
    NSURLRequest * request = [NSURLRequest requestWithURL:url];
    //异步加载
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse * response, NSData * data, NSError * error)
     {
         //展示一下由网址获得的html 数据格式
         // NSString * str = [[NSString alloc] initWithData:data encoding: NSUTF8StringEncoding];
         // NSLog(@"%@",str);
         //xpath解析html
         self.xpathParser=[[TFHpple alloc]initWithHTMLData:data];
         
         
         
         //图片
         NSArray * arrImgUrl = [self.xpathParser searchWithXPathQuery:@"//div[@id='news']//div//div[@class='pic']//a/img/@src"];
         //标题
         NSArray*arrTitle=[self.xpathParser searchWithXPathQuery:@"//div[@id='news']//div//div[@class='head']//h3/a"];
         //详情URL
        NSArray *urlArray=[self.xpathParser searchWithXPathQuery:@"//div[@id='news']//div//div[@class='head']//h3/a/@href"];
         //时间
         NSArray *timeArray=[self.xpathParser searchWithXPathQuery:@"//div[@id='news']//div//div[@class='head']//div[@class='meta']/span[@class='timer']"];
         //浏览次数
        NSArray *browseArray=[self.xpathParser searchWithXPathQuery:@"//div[@id='news']//div//div[@class='head']//div[@class='meta']//div[@class='funs']/span[@class='view']"];
         //内容
        NSArray *contentAry = [self.xpathParser searchWithXPathQuery:@"//div[@id='news']//div//div[@class='desc']//p"];
         //获取作者
         NSArray *authorrAry = [self.xpathParser searchWithXPathQuery:@"//div[@id='news']//div//div[@class='head']//div[@class='meta']//a"];
         
         
         
         for (int i=0; i<arrTitle.count; i++) {
             CHDHomeModel*homeModel=[CHDHomeModel new];

             //标题
             TFHppleElement *elementTitle =[arrTitle objectAtIndex:i];
             NSString *title = [elementTitle content];
             //内容
             TFHppleElement *elementContent =[contentAry objectAtIndex:i];
             NSString *content = [elementContent content];
             //图片
             TFHppleElement *elementImg =[arrImgUrl objectAtIndex:i];
             NSString *img = [elementImg content];
             //时间
             TFHppleElement *elementTime =[timeArray objectAtIndex:i];
             NSString *time = [elementTime content];
             
             //浏览次数
             TFHppleElement *elementLook =[browseArray objectAtIndex:i];
             NSString *lookcount = [elementLook content];
             //详情网址
             TFHppleElement *elementDetail =[urlArray objectAtIndex:i];
             NSString *detailUrl = [elementDetail content];

             homeModel.title=title;
             homeModel.content=content;
             homeModel.imgUrl=img;
             homeModel.time=time;
             homeModel.lookCount=lookcount;
             homeModel.detailUrl=detailUrl;
             
             
             [self.models addObject:homeModel];
         }

         //NSLog(@"%d",authorrAry.count);
         for (int i=0; i<authorrAry.count; i++)
         {
             
             TFHppleElement *element5=[authorrAry objectAtIndex:i];
             NSString *myContent5= [element5 content];
             if (i%3==0) {

                 [self.authorAry addObject:myContent5];
             }
             
         }
         


         //调用方法刷新表视图
         [self.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:NO];
         //停止刷新菊花
//         [self.activityIndicator stopAnimating ];
         [self hideHUD];
         
         
         
         
     }];


    
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    //设置表视图显示多少行
    if (self.tableView.hidden) {
        return self.nameAry.count;
    }else{
        return self.models.count;
        
    }

    
    
    
}
-(NSString*)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    
    return nil;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.tableView.hidden) {
        //单元格重用机制
        static NSString *CellIdentifier = @"CellIdentifier";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
            cell.textLabel.text = (NSString *)[self.nameAry objectAtIndex:indexPath.row];
            
            
        }
        return cell;
    }else{
        //根据nib自定义单元格
        static NSString *CellIdentifier = @"CellIdentifier";
        static BOOL isRegister=NO;
        if (!isRegister) {
            UINib *nib=[UINib nibWithNibName:@"newsCell" bundle:[NSBundle mainBundle]];
            [tableView registerNib:nib forCellReuseIdentifier:CellIdentifier];
            isRegister=YES;
            
        }
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        
        UIImageView *newImgView =(UIImageView*)[cell.contentView viewWithTag:60];
        UIImageView *image=(UIImageView *)[cell.contentView viewWithTag:110];
        UILabel*titleLabel=(UILabel*)[cell.contentView viewWithTag:111];
        UILabel*contentLabel=(UILabel*)[cell.contentView viewWithTag:112];
        UILabel*timeLabel=(UILabel*)[cell.contentView viewWithTag:113];
        UILabel*authorLabel=(UILabel*)[cell.contentView viewWithTag:114];
        UILabel*browseLabel=(UILabel*)[cell.contentView viewWithTag:115];
       
        UILabel*typeLabel=(UILabel*)[cell.contentView viewWithTag:117];
        CHDHomeModel*homeModel=[CHDHomeModel new];
        homeModel=self.models[indexPath.row];
        
        UILabel*shuLine=[[UILabel alloc]initWithFrame:CGRectMake(10, 0, 2, 170)];
        shuLine.backgroundColor=[UIColor blueColor];
        [cell.contentView addSubview:shuLine];
        UILabel*hengLine=[[UILabel alloc]initWithFrame:CGRectMake(10, 14, 15, 2)];
        hengLine.backgroundColor=[UIColor blueColor];
        [cell.contentView addSubview:hengLine];

 
        //[image setImageWithURL:[NSURL URLWithString:homeModel.imgUrl]];
        [image setImageWithURL:[NSURL URLWithString:homeModel.imgUrl] placeholderImage:[UIImage imageNamed:@"loading_info"]];
        titleLabel.text=homeModel.title;
        contentLabel.text=homeModel.content;
        timeLabel.text=homeModel.time;
        authorLabel.text=self.authorAry[indexPath.row];
        browseLabel.text=[NSString stringWithFormat:@"%@次浏览", homeModel.lookCount];
        typeLabel.text=self.button.titleLabel.text;
         newImgView.backgroundColor = [UIColor clearColor];
        //获取当前时间
        NSDate *now = [NSDate date];
       // NSLog(@"now date is: %@", now);
        
        NSCalendar *calendar = [NSCalendar currentCalendar];
        NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
        NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:now];
        
        int year = [dateComponent year];
        int month = [dateComponent month];
        int day = [dateComponent day];
        NSString*monthDate=[NSString stringWithFormat:@"%d",month];
        if (month<10) {
            monthDate=[NSString stringWithFormat:@"0%d",month];
        }
        NSString*nowTime=[NSString stringWithFormat:@"%d/%@/%d",year,monthDate,day];
        //NSLog(@"now=%@",nowTime);
        
        NSString*newsTime=[homeModel.time substringToIndex:10];
       // NSLog(@"news=%@",newsTime);
        if ([newsTime isEqualToString:nowTime]) {
            newImgView.image = [UIImage imageNamed:@"gamecenter_newtag"];
            newImgView.hidden = NO;
        }else{
            newImgView.hidden = YES;
        }
        
        

        return cell;
        
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.tableView.hidden) {
        return 20;
    }else{
        
        return 160;
        
    }
    
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.tableView.hidden) {
        [self clickView:indexPath.row];
    }else{
        
        CHDDetailsVC *datail=[[CHDDetailsVC alloc]init];
        CHDHomeModel*homeModel=self.models[indexPath.row];
        datail.urlStr=homeModel.detailUrl;
        datail.timeStr=homeModel.time;

        datail.authorr=self.authorAry[indexPath.row];
        
        [self.navigationController pushViewController:datail animated:YES];
        
    }
    
    
    
    
}

//上提刷新方法
- (void)addFooter
{
    MJRefreshFooterView *footer = [MJRefreshFooterView footer];
    footer.scrollView = self.tableView;
    footer.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        
        // 模拟延迟加载数据，因此2秒后才调用）
        // 这里的refreshView其实就是footer
        //NSLog(@"上拉");
        static int i=1;
        NSLog(@"%@",self.button.titleLabel.text);
        NSString*str=[NSString stringWithFormat:@"http://www.feng.com/%@/index_%d.shtml",self.button.titleLabel.text,i++];
            NSURL * url = [NSURL URLWithString:str];
            NSURLRequest * request = [NSURLRequest requestWithURL:url];
            
            [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse * response, NSData * data, NSError * error)
             {
                 //展示一下由网址获得的html 数据格式
                 // NSString * str = [[NSString alloc] initWithData:data encoding: NSUTF8StringEncoding];
                 // NSLog(@"%@",str);
                 self.xpathParser=[[TFHpple alloc]initWithHTMLData:data];
                 
                 //图片
                 NSArray * arrImgUrl = [self.xpathParser searchWithXPathQuery:@"//div[@id='news']//div//div[@class='pic']//a/img/@src"];
                 //标题
                 NSArray*arrTitle=[self.xpathParser searchWithXPathQuery:@"//div[@id='news']//div//div[@class='head']//h3/a"];
                 //详情URL
                 NSArray *urlArray=[self.xpathParser searchWithXPathQuery:@"//div[@id='news']//div//div[@class='head']//h3/a/@href"];
                 //时间
                 NSArray *timeArray=[self.xpathParser searchWithXPathQuery:@"//div[@id='news']//div//div[@class='head']//div[@class='meta']/span[@class='timer']"];
                 //浏览次数
                 NSArray *browseArray=[self.xpathParser searchWithXPathQuery:@"//div[@id='news']//div//div[@class='head']//div[@class='meta']//div[@class='funs']/span[@class='view']"];
                 //内容
                 NSArray *contentAry = [self.xpathParser searchWithXPathQuery:@"//div[@id='news']//div//div[@class='desc']//p"];
                 //获取作者
                 NSArray *authorrAry = [self.xpathParser searchWithXPathQuery:@"//div[@id='news']//div//div[@class='head']//div[@class='meta']//a"];
                 
                 
                 
                 for (int i=0; i<arrTitle.count; i++) {
                     CHDHomeModel*homeModel=[CHDHomeModel new];
                     
                     //标题
                     TFHppleElement *elementTitle =[arrTitle objectAtIndex:i];
                     NSString *title = [elementTitle content];
                     //内容
                     TFHppleElement *elementContent =[contentAry objectAtIndex:i];
                     NSString *content = [elementContent content];
                    
                     //图片
                     TFHppleElement *elementImg =[arrImgUrl objectAtIndex:i];
                     NSString *img = [elementImg content];
                     //时间
                     TFHppleElement *elementTime =[timeArray objectAtIndex:i];
                     NSString *time = [elementTime content];
                     
                     //浏览次数
                     TFHppleElement *elementLook =[browseArray objectAtIndex:i];
                     NSString *lookcount = [elementLook content];
                     //详情网址
                     TFHppleElement *elementDetail =[urlArray objectAtIndex:i];
                     NSString *detailUrl = [elementDetail content];
                     
                     homeModel.title=title;
                     homeModel.content=content;
                     homeModel.imgUrl=img;
                     homeModel.time=time;
                     homeModel.lookCount=lookcount;
                     homeModel.detailUrl=detailUrl;
                     
                    
                     [self.models addObject:homeModel];
                 }
               
                 NSLog(@"%d",authorrAry.count);
                 for (int i=0; i<authorrAry.count; i++)
                 {
                     
                     TFHppleElement *element5=[authorrAry objectAtIndex:i];
                     NSString *myContent5= [element5 content];
                     if (i%3==0) {
                         
                         [self.authorAry addObject:myContent5];
                     }
                     
                 }
                 

                 
                 // NSLog(@"%@",self.urlOneNewsArray);
                 [self.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:NO];
                 
                 
                 
                 
                 
             }];
        
        
        
        
        
        
        
        [self performSelector:@selector(doneWithView:) withObject:refreshView afterDelay:2.0];
        
        // NSLog(@"%@----开始进入刷新状态", refreshView.class);
    };
    _footer = footer;
    
}
//下拉刷新
- (void)addHeader
{
    
    MJRefreshHeaderView *header = [MJRefreshHeaderView header];
    header. scrollView= self.tableView;
    header.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        // 进入刷新状态就会回调这个Block
        //NSLog(@"下拉");
        // 增加5条假数据
        // 模拟延迟加载数据，因此2秒后才调用）
        // 这里的refreshView其实就是header
        
        
        [self performSelector:@selector(doneWithView:) withObject:refreshView afterDelay:2.0];
        
        //NSLog(@"%@----开始进入刷新状态", refreshView.class);
    };
    header.endStateChangeBlock = ^(MJRefreshBaseView *refreshView) {
        // 刷新完毕就会回调这个Block
        // NSLog(@"%@----刷新完毕", refreshView.class);
    };
    header.refreshStateChangeBlock = ^(MJRefreshBaseView *refreshView, MJRefreshState state) {
        // 控件的刷新状态切换了就会调用这个block
        switch (state) {
            case MJRefreshStateNormal:
                // NSLog(@"%@----切换到：普通状态", refreshView.class);
                break;
                
            case MJRefreshStatePulling:
                // NSLog(@"%@----切换到：松开即可刷新的状态", refreshView.class);
                break;
                
            case MJRefreshStateRefreshing:
                // NSLog(@"%@----切换到：正在刷新状态", refreshView.class);
                break;
            default:
                break;
        }
        
    };
    
    //[header beginRefreshing];
    _header = header;
}

- (void)doneWithView:(MJRefreshBaseView *)refreshView
{
    // 刷新表格
    [self.tableView reloadData];
    // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
    [refreshView endRefreshing];
}

















//检测网络状态
#pragma mark - notificationCenter 通知中心
-(void)notificationCenter{
    //初始化无网络view
    self.reachability = [[UIView alloc]initWithFrame:CGRectMake(0, 41, 320, 416)];
    self.reachability.backgroundColor = [UIColor colorWithRed:226/255.0 green:226/255.0 blue:226/255.0 alpha:1];
    
    //添加网络状态检测通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(reachTest:) name:kReachabilityChangedNotification object:nil];
    //为自身的实例变量host赋值
    self->hostReachability = [Reachability reachabilityWithHostName:@"www.baidu.com"];
    //开始监视网络状态
    [self->hostReachability startNotifier];
}
#pragma mark - 检测通知中心响应的方法
-(void)reachTest:(id)sender{
    //获取到网络的状态
    UIAlertView*alert;
    Reachability *curt = [sender object];
    if (curt == self->hostReachability) {
        //获取到当前网络状态
        NetworkStatus status = [curt currentReachabilityStatus];
        //判断网络状态 做响应的输出
        switch (status) {
            case NotReachable:
                isExistenceNetwork = NO;
                NSLog(@"无网络");
                alert =[[UIAlertView alloc]initWithTitle:@"注意" message:@"当前无网络！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
                break;
            case ReachableViaWiFi:
                isExistenceNetwork = YES;
                NSLog(@"wifi网络可用");
                //alert =[[UIAlertView alloc]initWithTitle:@"注意" message:@"当前正在使用WiFi网络！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
                
                break;
            case ReachableViaWWAN:
                isExistenceNetwork = YES;
                NSLog(@"2g/3g网络可用");
                alert =[[UIAlertView alloc]initWithTitle:@"注意" message:@"当前正在使用2g/3g网络！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
                break;
            default:
                break;
        }
    }
    //根据isExistenceNetwork的值判断需要执行的方法
    //[alert show];
    [self turnoff];
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if (buttonIndex==0) {
        [self turnoff];
    }
    
}
//根据isExistenceNetwork的值判断需要执行的方法的实现
-(void)turnoff{
    if (isExistenceNetwork == NO){
        [self showNoNetWork];
    }else{
        
        [self performSelector:@selector(downImgData)];
//        [self performSelector:@selector(downData)];
        
    }
}

#pragma mark - 没有网络时加载
-(void)showNoNetWork{
    self.reachability.frame=CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height);
    //自定义UIImageView
    UIImageView *imageView=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"no_network"]];
    imageView.frame=CGRectMake(123, 120, 74, 55);
    [self.reachability addSubview:imageView];
    //自定义两个label
    UILabel *customLabel1=[[UILabel alloc]initWithFrame:CGRectMake(100, 200, 120, 32)];
    customLabel1.text=@"网络连接失败";
    customLabel1.font=[UIFont boldSystemFontOfSize:20];
    customLabel1.textColor=[UIColor whiteColor];
    customLabel1.textColor=[UIColor colorWithRed:164/255.0 green:164/255.0 blue:164/255.0 alpha:1];
    customLabel1.backgroundColor=[UIColor clearColor];
    [self.reachability addSubview:customLabel1];
    
    UILabel *customLabel2=[[UILabel alloc]initWithFrame:CGRectMake(120, 240, 200, 32)];
    customLabel2.text=@"请刷新重试";
    customLabel2.font=[UIFont boldSystemFontOfSize:20];
    customLabel2.textColor=[UIColor colorWithRed:164/255.0 green:164/255.0 blue:164/255.0 alpha:1];
    customLabel2.backgroundColor=[UIColor clearColor];
    [self.reachability addSubview:customLabel2];
    [self.view addSubview:self.reachability];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
